#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <string.h>
#include <stdlib.h>
//#include "logger2.h"

#define INFO 0
#define WARN 1
#define ERROR 2
//print logs with level <= error_level

#define size 500

int error_level = ERROR; //print all logs
 
FILE *fd;
int SESSION_TRACKER = 0;
char buffer[size];
int free_space = size;

void set_error_level(int level1){
    if ((level1 >= INFO) && (level1 <= ERROR)){
	error_level = level1;
    }
}
 
char* print_time(){
    time_t t;
    char *buf;     
    time(&t);
    buf = (char*) malloc(strlen(ctime(&t)) + 1);     
    snprintf(buf, strlen(ctime(&t)), "%s ", ctime(&t));   
    return buf;
}

void fill_buffer(char* tmp_buffer){
    char end_buffer[300], beg_buffer[300];
    int size_of_buffer = strlen(tmp_buffer);
    if (size_of_buffer > free_space){
	snprintf(end_buffer, free_space+1, "%s", tmp_buffer);
	sprintf(beg_buffer, "%s", tmp_buffer+free_space);
	strcat(buffer, end_buffer);
	fprintf(fd, "%s", buffer);
	strcpy(buffer, beg_buffer);
	free_space = size - strlen(beg_buffer);
    }
    else if (size_of_buffer == free_space){
	strcat(buffer, tmp_buffer);
	fprintf(fd, "%s\n", buffer);
	strcpy(buffer, "");
	free_space = size;
    }
    else {
	strcat(buffer, tmp_buffer);
	free_space = free_space - size_of_buffer;
    }
}
	  
void log_print(int level, char* filename, int line, char *ptr,...){
    if (SESSION_TRACKER > 0){
	fd = fopen("log.txt", "a+");
    }
    else{
	fd = fopen("log.txt", "w");
    }
    char vargs_buffer[200], tmp_buffer[300], err_buffer[6];
    char* time_buffer = print_time();
    if (level == INFO)
	strcpy(err_buffer, "INFO");
    if (level == WARN)
	strcpy(err_buffer, "WARN");
    if (level == ERROR)
	strcpy(err_buffer, "ERROR");
    if (level > error_level){     
	if (level == ERROR){
	    fprintf(fd, "%s", buffer);
	}  
	SESSION_TRACKER = 1;
	free(time_buffer);
	fclose(fd);
	return;
    }
    va_list ap;
    va_start(ap, ptr);
    vsprintf(vargs_buffer, ptr, ap);
    va_end(ap);
    sprintf(tmp_buffer, "%s  %s: %s  [%s][line: %d]\n", time_buffer, err_buffer, vargs_buffer, filename, line);
//    printf("%s\n", tmp_buffer);
    fill_buffer(tmp_buffer);
    free(time_buffer);
    if ((strcmp(vargs_buffer, "the program successfully completed") == 0) || (strcmp(err_buffer, "ERROR")) == 0){
	fprintf(fd, "%s", buffer);
    }
    SESSION_TRACKER = 1;
    fclose(fd);
}